import json

from javalang.ast import Node
from javalang.tree import CompilationUnit


class ClassDumper:
    @staticmethod
    def dump_class(file_path: str, cu: CompilationUnit):
        with open(file_path, 'w', encoding='utf-8') as fp:
            fp.write(json.dumps(cu, indent=2, default=ClassDumper.node2dict))

    @staticmethod
    def node2dict(obj):
        if isinstance(obj, Node):
            new_dict = {}
            new_dict.update(obj.__dict__)
            if '_position' in new_dict:
                pos_item = new_dict.pop('_position')
                if pos_item is not None:
                    new_dict['line'] = pos_item[0]
            new_dict['node'] = type(obj).__name__
            return new_dict
        elif isinstance(obj, set):
            return list(obj)
        else:
            return obj